import { readFileSync, copySync, existsSync, mkdirsSync, readJsonSync, writeFileSync } from 'fs-extra';
import fs from 'fs';
import { join } from 'path';
const { shell } = require('electron');
/**
 * @zh 如果希望兼容 3.3 之前的版本可以使用下方的代码
 * @en You can add the code below if you want compatibility with versions prior to 3.3
 */
// Editor.Panel.define = Editor.Panel.define || function(options: any) { return options }

let config = {
	m_account: "",
	m_param: "",
};

module.exports = Editor.Panel.define({
	listeners: {
		show() { console.log('show'); },
		hide() { console.log('hide'); },
	},
	template: readFileSync(join(__dirname, '../../../source/panels/default/index.html'), 'utf-8'),
	style: readFileSync(join(__dirname, '../../../source/panels/default/index.css'), 'utf-8'),
	$: {
		m_account: "#m_account",
		m_param: "#m_param",
		btnDeclare: "#btnDeclare",
		btnDrawCallCheck: "#btnDrawCallCheck",
		btnOpenMore: "#btnOpenMore",
		btnOpenSingle: "#btnOpenSingle",
	},
	methods: {
		folder(assetInfo: AssetInfo) {
			var num = 0;
			Editor.assetdb.queryAssets(assetInfo.url + '/**/*', ['scene', 'prefab'], (error, results) => {
				if (!error) {
					results.forEach((result) => {
						this.prefab(result);
						num++;
					});
				}
			});

		},

		prefab(assetInfo: AssetInfo) {
			let declareName = Editor.Utils.Path.basenameNoExt(assetInfo.url);
			let content = `declare interface ${declareName}_Declare {\n`;
			let json = readJsonSync(assetInfo.file);
			let baseNode = json[0];
			let rootNode = json[1];
			let outputFunc = function (nodeInfo) {
				let name = nodeInfo['_name'];
				let type = nodeInfo['__type__'];
				if (name !== undefined && type !== undefined && name !== declareName) {
					content += '\t' + `'${name}': ${type};` + '\n';
				}

				let children = nodeInfo['_children'];
				if (!children || children.lenght < 1) return;

				for (const childInfo in children) {
					if (children.hasOwnProperty(childInfo)) {
						const element = children[childInfo];
						let childID = element['__id__'];
						let childNode = json[childID];
						outputFunc(childNode);
					}
				}
			};
			outputFunc(rootNode);
			content += '}\n';

			let fileName = declareName + '.d.ts';
			let rootPath = join(Editor.Project.path, 'uideclare');
			// console.log(`rootPath：${rootPath} `);
			try {
				writeFileSync(join(rootPath, fileName), content);
				console.log(`生成 ${fileName} 成功`);
			} catch (error) {
				console.error(`生成 ${fileName} 失败`);
			}
		},

		async getSelectAssetInfo() {
			let uuidArrays = Editor.Selection.getSelected('asset');
			if (uuidArrays.length <= 0) {
				return;
			}
			let selectionUUid = uuidArrays[0];
			let assetInfo: AssetInfo | undefined = await this.getAssetInfoByUUID(selectionUUid)
			// Editor.Dialog.info('assetInfo !' + assetInfo?.name);
			// console.log('assetInfo name:' + assetInfo?.name + ' type:' + assetInfo?.type);

			if (!assetInfo) {
				// Editor.Dialog.warn('Please select a Prefab !');
				console.error(`Please select a Prefab !`);
				return;
			}
			let assetType = assetInfo.type;
			if (assetType === 'folder') {
				this.folder(assetInfo);
			} else if (assetType === 'cc.Prefab') {
				this.prefab(assetInfo);
			} else {
				console.error(`Please select a Prefab 2 !`)
			}
			// return assetInfo;
		},

		async getAssetInfoByUUID(uuid: string): Promise<AssetInfo | undefined> {
			// 获取资源信息
			const assetInfo = await Editor.Message.request('asset-db', 'query-asset-info', uuid);
			if (assetInfo) {
				// console.log(`资源信息: ${JSON.stringify(assetInfo)}`);
				return assetInfo
			}
			console.error(`无法找到 UUID 为 ${uuid} 的资源`);
			return undefined;
		},

		onClickBtnDeclare() {
			// console.log(`onClickBtnDeclare:`);
			this.getSelectAssetInfo();
		},


		onClickBtnOpenMore(account: string, param: string) {
			console.log(`onClickBtnOpenMore: ${account}, ${param}`);

			var framesrc = "http://localhost:7456/assets/resources/native/more.html?furl=../../../&";
			if (account) {
				framesrc += "account=" + account;
			}
			if (param) {
				framesrc += "&" + param;
			}
			shell.openExternal(framesrc);

			console.log(`onClickBtnOpenMore: ${framesrc}`);
		},
		onClickBtnSingle(account: string, param: string) {
			// htmlrun.opensingle(account, param);
			console.log(`onClickBtnSingle:`);
			var gamesrc = "http://localhost:7456/assets/resources/native/H5GameScene.html?url=../../../%3F";
			if (account) {
				account = account.split(",")[0];
				gamesrc += "account%3D" + account;
			}
			if (param) {
				param = param.replace(/=/g, '%3D');
				param = param.replace(/&/g, '%26');
				gamesrc += "%26" + param;
			}
			shell.openExternal(gamesrc);
		},

		onClickBtnDrawCallCheck() {
			console.log(`onClickBtnDrawCallCheck:`);
		}
	},

	ready() {
		console.log(`game tool ready`);
		// 事件监听
		// 多开
		let outpath = join(Editor.Project.path, "/library");
		let htmlpath = join(Editor.Project.path, '/extensions/game-tools/html/'); // Path.join(Editor.Project.path,"/packages/htmlTool/html");
		let files = fs.readdirSync(htmlpath);
		files.forEach(function (filename) {
			//获取当前文件的绝对路径
			let filedir = join(htmlpath, filename);
			let outdir = join(outpath, filename);
			copySync(filedir, outdir);
		});

		// UI 声明
		let rootPath = join(Editor.Project.path, 'uideclare');

		if (!existsSync(rootPath)) {
			mkdirsSync(rootPath);
		}

		let saveCall = () => {
			//@ts-ignore
			config.m_account = this.$.m_account.value;
			//@ts-ignore
			config.m_param = this.$.m_param.value;
		};

		//@ts-ignore
		if (this.$.m_account) {
			this.$.m_account.addEventListener("confirm", () => {
				//@ts-ignore
				// Editor.Message.send("textmeshpro-tool", "change-config", "textStr", this.$.textStr.value);
				saveCall();
			});
		}

		if (this.$.m_param) {
			this.$.m_param.addEventListener("confirm", () => {
				//@ts-ignore
				// Editor.Message.send("textmeshpro-tool", "change-config", "textStr", this.$.textStr.value);
				saveCall();
			});
		}

		if (this.$.btnOpenMore) {
			this.$.btnOpenMore.addEventListener("confirm", () => {
				console.log(`onClickBtnOpenMore: 1`);
				//@ts-ignore
				Editor.Message.send("game-tools", "click-btn-openmore", this.$.m_account.value, this.$.m_param.value);
			});
		}

		if (this.$.btnOpenSingle) {
			this.$.btnOpenSingle.addEventListener("confirm", () => {
				console.log(`btnOpenSingle: 1`);
				//@ts-ignore
				Editor.Message.send("game-tools", "click-btn-single", this.$.m_account.value, this.$.m_param.value);
			});
		}
		if (this.$.btnDeclare) {
			//@ts-ignore
			this.$.btnDeclare.addEventListener("click", () => {
				Editor.Message.send("game-tools", "click-btn-declare");
			});
		}

		if (this.$.btnDrawCallCheck) {
			//@ts-ignore
			this.$.btnDrawCallCheck.addEventListener("click", () => {
				Editor.Message.send("game-tools", "click-btn-drawCallCheck");
			});
		}
	},
	beforeClose() { },
	close() { },
});
